/**
 * Created by zsyoung on 2017/9/4.
 */

$(function () {
    initializeAppSelect();
});

function initializeAppSelect() {
    getAppList(bindAppSelect, GetQueryString("appId"));
}

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r !== null)
        return decodeURI(r[2]);
    else
        return null;
}

function getAppList(callback, appId) {
    var url = "/cykmr/app/listAll";
    $.ajax({
        url: url,
        dataType: 'json',
        success: function (data) {
            callback(data, appId);
            (function () {
                [].slice.call(document.querySelectorAll('select.cs-select')).forEach(function (el) {
                    var item = new SelectFx(el);
                    item.options.onChange = function (data) {
                        if (data !== "选择App列表") {
                            dataAnalysis(data);
                        }
                    };
                });
            })();
        }
    });
}

function bindAppSelect(data, appId) {
    var $appSelect = $("#appSelect");
    data.forEach(function (item) {
        if (appId === item.appId) {
            $appSelect.append($("<option selected></option>").val(item.appId).text(item.appName));
            dataAnalysis(item.appId);
        } else {
            $appSelect.append($("<option></option>").val(item.appId).text(item.appName));
        }
    });
}

function dataAnalysis(appId) {
    var url = "/cykmr/analysis/getAnalysisData";
    dataExport(appId);
    $.ajax({
        type: "post",
        dataType: 'json',
        url: url,
        data: {
            appId: appId,
            limit: 25
        },
        success: function (data) {
            function sortNumber(a, b) {
                return b[1] - a[1]
            }

            var dataArr = [];
            for (var i in data) {
                dataArr.push([i, data[i][0]]);
            }
            barShow(dataArr.sort(sortNumber));
            pieShow(dataArr.sort(sortNumber));
        }
    });
}

function dataExport(appId) {
    var $dataExport = $("#data_export");
    $dataExport.click(function () {
        window.location.href = "/cykmr/analysis/exportToExcel?appId=" + appId;
    })
}